package hn.cch.druid.configuration;

import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.cache.interceptor.KeyGenerator;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.cache.RedisCacheManager;
import org.springframework.data.redis.core.RedisTemplate;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

/**
 * @author CCH
 * @version 2018.08.30
 */

@Configuration
@EnableCaching
public class RedisConfiguration {
    @Bean
    public CacheManager cacheManager(RedisTemplate redisTemplate) {
        RedisCacheManager redisCacheManager = new RedisCacheManager
                (redisTemplate);
        redisCacheManager.setDefaultExpiration(43200);//缓存有效时间12小时
        return redisCacheManager;
    }

    @Bean
    public KeyGenerator className() {
        return (o, method, objects) -> {
            StringBuffer stringBuffer = new StringBuffer();
            stringBuffer.append(o.getClass().getName() + "." + method
                    .getName() + ":");
            for (Object object : objects) {
                stringBuffer.append(object.toString());
            }
            return stringBuffer.toString();
        };
    }

    @Bean
    public KeyGenerator objectId() {
        return new KeyGenerator() {
            @Override
            public Object generate(Object o, Method method, Object... objects) {

                StringBuffer stringBuffer = new StringBuffer();
                stringBuffer.append(o.getClass().getName() + "." + method
                        .getName() + ":");
                for (Object object : objects) {
                    try {
                        stringBuffer.append(object.getClass().getMethod
                                ("getId", null).invoke(object, null).toString
                                ());
                    } catch (IllegalAccessException | NoSuchMethodException |
                            InvocationTargetException e) {
                        e.printStackTrace();
                    }
                }
                return stringBuffer.toString();
            }
        };
    }
}
